
package com.spsy.pay.mq.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;


@Component
@RabbitListener(queues = "TestDirectQueue2206a4")//监听的队列名称 TestDirectQueue
public class DirectReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitHandler
    public void process(Map map, Message message, Channel channel) {
        System.out.println("======>DirectReceiver2206a4 消费者收到消息  : " + map.toString());

        try {

            String messageId = (String) map.get("messageId");

            //如果有的话，就要消费
            if(this.redisTemplate.hasKey(messageId)){
                this.redisTemplate.delete(messageId);
                //处理相关业务逻辑
                System.out.println("处理相关业务逻辑");

            }else{


                System.out.println("消息已经被消息");
                //确认回调
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

            }

            //修改订单数据
           /* System.out.println("testMessage:"+ JSON.toJSONString(testMessage));
            //确认回调
            ;*/
            //确认回调
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

            //System.out.println("从新入队");


            //channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        } catch (Exception e) {
            try {
                //处理失败、拒绝消息并重新入队
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

        }
    }
}

